<?php
namespace app\index\controller;
use app\index\model\CrmMedia;
use app\index\model\CrmMediaNext;
use excel\Excels as excels;
use polyv\Blw;
use app\index\model\UserCourse;
use app\index\model\GoodsNext;

class Course extends Base
{
    public $course;
    public $subcourse;
    public function __construct()
    {
        parent::__construct();
        $this->course = model('Goods');
        $this->subcourse = model('GoodsNext');
    }

    // 新增课程
    public function courseAdd()
    {
        $data = input();//token凭证 search_type课程分类 type课程类型 title课程标题 desc课程描述 pic1老师头像 name老师名称 teacher老师职称 link链接 status状态 is_next子课程 channel频道

        $validate = new \app\index\validate\Goods;
        if ($validate->check($data)) {
            if (!empty($data['pic1'])) {
                $data['thumb'] = $this->thumbPic($data['pic1'], 200, 112);
            }
            $data['time'] = strtotime($data['time']);
            $this->course->save($data);
            apiReturn(200,'新增课程成功');
        }else{
            apiReturn(201,$validate->getError());
        }
    }

    // 课程列表
    public function courseList()
    {
        $data = input();
        $where = [];
        if (isset($data['search_type_type'])) {
            if ($data['search_type_type'] == 1) {
                $where['search_type'] = array('in','1,2,3');
            }elseif ($data['search_type_type'] == 2) {
                $where['search_type'] = array('in','4,5,6');
            }elseif ($data['search_type_type'] == 3) {
                $where['search_type'] = array('in','7,8,9');
            }elseif ($data['search_type_type'] == 4) {
                $where['search_type'] = array('in','10');
            }elseif ($data['search_type_type'] == 5) {
                $where['search_type'] = array('in','11,12,13');
            }elseif ($data['search_type_type'] == 6) {
                $where['search_type'] = array('in','14,15,16');
            }elseif ($data['search_type_type'] == 7) {
                $where['search_type'] = array('in','17');
            }elseif ($data['search_type_type'] == 8) {
                $where['search_type'] = array('in','18');
            }elseif ($data['search_type_type'] == 9) {
                $where['search_type'] = array('in','19');
            }elseif ($data['search_type_type'] == 10) {
                $where['search_type'] = array('in','20');
            }else{
                apiReturn(201,'分类错误');
            }
        }else{
            $where['search_type'] = array('in','1,2,3');
        }
        if (isset($data['type'])) {
            if (!empty($data['type'])) {
                $where['type'] = $data['type'];
            }
        }
        if (isset($data['title'])) {
            if (!empty($data['title'])) {
                $where['title'] = array('like','%'.$data['title'].'%');
            }
        }
        $courseList = $this->course->where($where)->order('sort DESC ,time DESC')->limit(($data['page']-1)*$data['rows'],$data['rows'])->select();
        foreach ($courseList as $key => $value) {
            $courseList[$key]['numbers'] = db('goods_phone')->where('course_id',$value['id'])->count();
        }
        $count = $this->course->where($where)->count();

        $datas = array(
            'courseList'=>$courseList,
            'count'=>$count
        );

        apiReturn(200,'获取课程列表成功',$datas);
    }

    // 课程信息
    public function courseInfo()
    {
        $data = input();//token id

        $courseInfo = $this->course->find($data['id']);
        // if (strpos($courseInfo['pic1'],'uploads') !== false) {
        //     $courseInfo['pic1'] = 'https://x.xuexiang.com.cn'.$courseInfo['pic1'];
        // }
        // $courseInfo['pic1'] = array($courseInfo['pic1']);

        // $month = substr($courseInfo['title'], 0,2);
        // $day = substr($courseInfo['title'], 2,2);
        // var_dump('20'.$year.'-'.$month.'-'.$day.' 19:00:00');exit;

        // $courseInfo['time'] = strtotime('2022'.'-'.$month.'-'.$day.' 19:00:00');

        apiReturn(200,'获取课程信息成功',$courseInfo);
    }

    // 修改课程
    public function courseEdit()
    {
        $data = input();//token凭证 id课程id search_type课程分类 type课程类型 title课程标题 desc课程描述 pic1老师头像 name老师名称 teacher老师职称 link链接 status状态 is_next子课程 channel频道
        $validate = new \app\index\validate\Goods;
        if ($validate->check($data)) {
            $pic1 = $this->course->where('id',$data['id'])->value('pic1');
            if (!empty($data['pic1'])) {
                if ($pic1 != $data['pic1']) {
                    $data['thumb'] = $this->thumbPic($data['pic1'], 200, 112);
                }
            }
            unset($data['date']);
            $data['time'] = strtotime($data['time']);
            $this->course->allowField(true)->save($data,['id'=>$data['id']]);
            apiReturn(200,'修改课程成功');
        }else{
            apiReturn(201,$validate->getError());
        }
    }

    // 删除课程
    public function courseDelete()
    {
        $data = input();//token凭证 id课程id

        if (empty($data['id'])) {
            apiReturn(201,'课程id为空');
        }
        $this->course->where('id',$data['id'])->delete();
        apiReturn(200,'删除课程成功');
    }

    // 课程状态设置
    public function courseStatus()
    {
        $data = input();//token凭证 id课程id

        $status = $this->course->where('id',$data['id'])->value('status');
        $datas['status'] = ($status == 1) ? 0 : 1;
        $this->course->save($datas,['id'=>$data['id']]);
        apiReturn(200,'修改状态成功');
    }
    // 有无子课程设置
    public function courseNext()
    {
        $data = input();//token凭证 id课程id

        $is_next = $this->course->where('id',$data['id'])->value('is_next');
        $datas['is_next'] = ($is_next == 1) ? 0 : 1;
        $this->course->save($datas,['id'=>$data['id']]);
        apiReturn(200,'修改成功');
    }

    // 子课程列表
    public function subCourseList()
    {
        $data = input();//token凭证 goods_id课程id title课程标题 rows每页条数 page页码

        if (isset($data['title'])) {
            if (!empty($data['title'])) {
                $where['title'] = array('like','%'.$data['title'].'%');
            }
        }
        $where['goods_id'] = $data['goods_id'];

        $subCourseList = $this->subcourse->field('id,goods_id,title,desc,status,date,link,sort_order,channel,kaibo_time')->where($where)->order('sort_order ASC,date ASC')->limit(($data['page']-1)*$data['rows'],$data['rows'])->select();
        $count = $this->subcourse->where($where)->count();
//        foreach ($subCourseList as &$value){
//            $value['viewers']= $this->link($value['link'])['count'];
//        }
        $datas = array(
            'subCourseList'=>$subCourseList,
            'count'=>$count
        );

        apiReturn(200,'获取子课程列表成功',$datas);
    }
    public function link($link){
        $link= explode('/',$link);
        $channel = (int)$link[count($link)-1];
        $viewers = Blw::get_realtime_viewers($channel);
        $data['count']=0;
        if(isset($viewers['data'][0]['count'])){
            $data=$viewers['data'][0];

        }
        return $data;
    }

    public function viewers(){
        $link = input('link');
        $res = $this->link($link);
        if($res['count']==0){
            $res['time']=date("H:i:s");
        }
        apiReturn(200,'ok',$res);
    }

    //子课程导入
    public function subcourseImport()
    {
        $data = input();//token url文件路径 goods_id课程id

        if (empty($data['goods_id'])) {
            apiReturn(201,'营期id不存在');
        }
        $file = request()->file('file');
        if (empty($file)) {
            apiReturn(201,'文件不能为空');
        }
        $url = $this->uploadFile($file,2);
        if (empty($url)) {
            apiReturn(201,'文件不存在');
        }
        // var_dump($url);exit;
        $data_array = excels::readExcelFile($url,2);
        if (empty($data_array)) {
            apiReturn(204,'文件内容为空或读取失败');
        }
        foreach ($data_array as $key => $value) {
            if ($key >= 1) {
                if (!empty($value[0]) && !empty($value[1]) && !empty($value[2]) && !empty($value[3])) {
                    $datas = array(
                        'goods_id'=>$data['goods_id'],
                        'title'=>$value[0],
                        'desc'=>$value[1],
                        'status'=>1,
                        'date'=>time(),
                        'link'=>$value[2],
                        'sort_order'=>$value[3]
                    );
                    if (strpos($value[1],'日') && strpos($value[1],'月') && strpos($value[1],'--')) {
                        $year = date("Y",time());
                        $shijian = explode('日', $value[1]);
                        $shijian1 = explode('月', $shijian[0]);
                        $hourminute1 = explode('--', $shijian[1]);
                        $hourminute = trim($hourminute1[0]);
                        if ($shijian1[0] == '01' || $shijian1[0] == '02' || $shijian1[0] == '03' || $shijian1[0] == '04' || $shijian1[0] == '05' || $shijian1[0] == '06') {
                            $year = '2024';
                        }
                        $kaibo_time = $year.'-'.$shijian1[0].'-'.$shijian1[1].' '.$hourminute.':00';
                        $datas['kaibo_time'] = strtotime($kaibo_time);
                    }else{
                        apiReturn(201,'第'.$key.'行课程时间格式错误，格式为01月01日 19:00--21:00');
                    }
                    db('goods_next')->insert($datas);
                }else{
                    apiReturn(201,'第'.$key.'行有空数据');
                }
            }
        }
        apiReturn(200,'导入成功');
    }

    // 新增子课程
    public function subCourseAdd()
    {
        $data = input();//token凭证 goods_id课程id title子课程标题 desc子课程时间 link链接 status状态 channel频道

        $validate = new \app\index\validate\GoodsNext;
        if ($validate->check($data)) {
            if (strpos($data['desc'],'日') && strpos($data['desc'],'月') && strpos($data['desc'],'--')) {
                $year = date("Y",time());
                $shijian = explode('日', $data['desc']);
                $shijian1 = explode('月', $shijian[0]);
                $hourminute1 = explode('--', $shijian[1]);
                $hourminute = trim($hourminute1[0]);
                if ($shijian1[0] == '01' || $shijian1[0] == '02' || $shijian1[0] == '03' || $shijian1[0] == '04' || $shijian1[0] == '05' || $shijian1[0] == '06') {
                    $year = '2024';
                }
                $kaibo_time = $year.'-'.$shijian1[0].'-'.$shijian1[1].' '.$hourminute.':00';
                $data['kaibo_time'] = strtotime($kaibo_time);
            }else{
                apiReturn(201,'课程时间格式错误，格式为01月01日 19:00--21:00');
            }
            $this->subcourse->save($data);
            apiReturn(200,'新增子课程成功');
        }else{
            apiReturn(201,$validate->getError());
        }
    }
    
    // 获取子课程信息
    public function subCourseInfo()
    {
        $data = input();//token id
        $subCourseInfo = $this->subcourse->find($data['id']);
        apiReturn(200,'获取子课程信息成功',$subCourseInfo);
    }

    // 修改子课程
    public function subCourseEdit()
    {
        $data = input();//token凭证 id子课程id title子课程标题 desc子课程时间 link链接 status状态 channel频道

        $validate = new \app\index\validate\GoodsNext;
        if ($validate->check($data)) {
            if (strpos($data['desc'],'日') && strpos($data['desc'],'月') && strpos($data['desc'],'--')) {
                $year = date("Y",time());
                $shijian = explode('日', $data['desc']);
                $shijian1 = explode('月', $shijian[0]);
                $hourminute1 = explode('--', $shijian[1]);
                $hourminute = trim($hourminute1[0]);
                if ($shijian1[0] == '01' || $shijian1[0] == '02' || $shijian1[0] == '03' || $shijian1[0] == '04' || $shijian1[0] == '05' || $shijian1[0] == '06') {
                    $year = '2024';
                }
                $kaibo_time = $year.'-'.$shijian1[0].'-'.$shijian1[1].' '.$hourminute.':00';
                $data['kaibo_time'] = strtotime($kaibo_time);
            }else{
                apiReturn(201,'课程时间格式错误，格式为01月01日 19:00--21:00');
            }
            $this->subcourse->save($data,['id'=>$data['id']]);
            apiReturn(200,'修改子课程成功');
        }else{
            apiReturn(201,$validate->getError());
        }
    }

    // 删除子课程
    public function subCourseDelete()
    {
        $data = input();//token凭证 id子课程id

        if (empty($data['id'])) {
            apiReturn(201,'子课程id为空');
        }
        $this->subcourse->where('id',$data['id'])->delete();
        apiReturn(200,'删除子课程成功');
    }

    // 子课程排序设置
    public function subCourseSort()
    {
        $data = input();//token凭证 id子课程id sort_order排序

        $exist = $this->subcourse->where('id',$data['id'])->find();
        if (empty($exist)) {
            apiReturn(201,'子课程不存在');
        }else{
            if ($exist['sort_order'] == $data['sort_order']) {
                apiReturn(200,'修改排序成功');
            }else{
                $this->subcourse->save($data,['id'=>$data['id']]);
            }
        }
        apiReturn(200,'修改排序成功');
    }

    // 子课程状态设置
    public function subCourseStatus()
    {
        $data = input();//token凭证 id子课程id

        $status = $this->subcourse->where('id',$data['id'])->value('status');
        $datas['status'] = ($status == 1) ? 0 : 1;
        $this->subcourse->save($datas,['id'=>$data['id']]);
        apiReturn(200,'修改状态成功');
    }

    // 白名单列表
    public function baimingdanList()
    {
        $data = input();//token凭证 course_id课程id phone电话 starttime开始时间 endtime结束时间 status是否进入课程(-1 1 0) rows page

        if (empty($data['course_id'])) {
            apiReturn(201,'课程id为空');
        }
        if (!empty($data['phone'])) {
            $where['phone'] = array('like','%'.$data['phone'].'%');
        }
        if (!empty($data['starttime']) && !empty($data['endtime'])) {
            $where['date'] = array(array('egt',strtotime($data['starttime'])),array('elt',strtotime($data['endtime'])));
        }
        if ($data['status'] != -1) {
            $where['status'] = $data['status'];
        }
        $where['course_id'] = $data['course_id'];

        $baimingdanList = db('goods_phone')->where($where)->order('date DESC')->limit(($data['page']-1)*$data['rows'],$data['rows'])->select();
        $count = db('goods_phone')->where($where)->count();

        $datas = array(
            'baimingdanList'=>$baimingdanList,
            'count'=>$count
        );

        apiReturn(200,'获取白名单列表成功',$datas);
    }

    // 新增白名单
    public function baimingdanAdda()
    {
        $data = input();//token凭证 course_id课程id phone电话

        if (empty($data['course_id'])) {
            apiReturn(201,'课程id不能为空');
        }
        if (empty($data['phone'])) {
            apiReturn(202,'电话不能为空');
        }

        $exist = db('goods_phone')->where(array('course_id'=>$data['course_id'],'phone'=>trim($data['phone'])))->find();
        if (empty($exist)) {
            $datas = array(
                'course_id'=>$data['course_id'],
                'phone'=>trim($data['phone']),
                'date'=>time()
            );
            db('goods_phone')->insert($datas);
        }else{
            $datas = array(
                'date'=>time()
            );
            db('goods_phone')->where(array('id'=>$exist['id']))->update($datas);
        }
        self::clearCustomerCache(trim($data['phone']));
        apiReturn(200,'添加白名单成功');
    }

    // 删除白名单
    public function baimingdanDelete()
    {
        $data = input();//token凭证 id白名单id

        if (empty($data['id'])) {
            apiReturn(201,'白名单id为空');
        }
        $phone = db('goods_phone')->where('id',$data['id'])->value('phone');
        db('goods_phone')->delete($data['id']);
        self::clearCustomerCache($phone);
        apiReturn(200,'删除白名单成功');
    }

    // 批量删除白名单
    public function baimingdanDeleteIds()
    {
        $data = input();//token凭证 ids白名单id集合(1,2,3)
        if (empty($data['ids'])) {
            apiReturn(201,'未勾选白名单');
        }
        foreach ($data['ids'] as $key => $value) {
            db('goods_phone')->where('id',$value)->delete();
        }
        apiReturn(200,'批量删除成功');
    }

    // 导入白名单
    public function baimingdanImport()
    {
        $data = input();//token凭证 course_id课程id url文件路径 action_type操作类型(1导入 2导入删除)
        if (empty($data['course_id'])) {
            apiReturn(201,'课程id不能为空');
        }
        if (empty($data['url'])) {
            apiReturn(202,'文件不能为空');
        }
        if (empty($data['action_type'])) {
            apiReturn(203,'操作类型不能为空');
        }
        $data_array = excels::readExcelFile($data['url']);
        if (empty($data_array)) {
            apiReturn(204,'文件内容为空或读取失败');
        }
        if ($data['action_type'] == 1) {
            foreach ($data_array as $key => $value) {
                if ($key >= 1) {
                    if (!empty($value[1])) {
                        $exist = db('goods_phone')->where(array('course_id'=>$data['course_id'],'phone'=>trim($value[1])))->find();
                        if (empty($exist)) {
                            $datas = array(
                                'course_id'=>$data['course_id'],
                                'phone'=>trim($value[1]),
                                'date'=>time()
                            );
                            db('goods_phone')->insert($datas);
                        }else{
                            $datas = array(
                                'date'=>time()
                            );
                            db('goods_phone')->where(array('id'=>$exist['id']))->update($datas);
                        }
                    }
                }
            }
            apiReturn(200,'导入成功');
        }elseif ($data['action_type'] == 2) {
            foreach ($data_array as $key => $value) {
                if ($key >= 1) {
                    if (!empty($value[0])) {
                        $exist = db('goods_phone')->where(array('course_id'=>$data['course_id'],'phone'=>trim($value[1])))->find();
                        if (!empty($exist)) {
                            db('goods_phone')->where(array('course_id'=>$data['course_id'],'phone'=>trim($value[1])))->delete();
                        }
                    }
                }
            }
            apiReturn(200,'删除成功');
        }else{
            apiReturn(205,'操作类型错误');
        }
    }

    // 新增修改课程用户
    public function userCourseAdd()
    {
        $data = input();//token id realname phone
        if (empty($data['realname'])) {
            apiReturn(201,'姓名不能为空');
        }
        if (empty($data['phone'])) {
            apiReturn(202,'电话不能为空');
        }
        $datas = array(
            'realname'=>$data['realname'],
            'phone'=>$data['phone'],
            'date'=>time()
        );
        if (empty($data['id'])) {
            $exist = db('user_course')->where('phone',$data['phone'])->find();
            if (empty($exist)) {
                db('user_course')->insert($datas);
            }else{
                db('user_course')->where('id',$exist['id'])->update($datas);
            }
            apiReturn(200,'新增成功');
        }else{
            db('user_course')->where('id',$data['id'])->update($datas);
            apiReturn(200,'修改成功');
        }
    }

    // 课程用户列表
    public function userCourseList()
    {
        $data = input();//token nickname微信昵称 realname姓名 rows page

        $where = array();
        if (isset($data['nickname'])) {
            if (!empty($data['nickname'])) {
                $where['nickname'] = array('like','%'.$data['nickname'].'%');
            }
        }
        if (isset($data['realname'])) {
            if (!empty($data['realname'])) {
                $where['realname'] = array('like','%'.$data['realname'].'%');
            }
        }
        if (isset($data['phone'])) {
            if (!empty($data['phone'])) {
                $where['phone'] = array('like','%'.$data['phone'].'%');
            }
        }

        $userCourseList = db('user_course')->field('id,nickname,headimgurl,realname,phone,date')->where($where)->order('date DESC')->limit(($data['page']-1)*$data['rows'],$data['rows'])->select();
        $count = db('user_course')->where($where)->count();

        $datas = array(
            'userCourseList'=>$userCourseList,
            'count'=>$count
        );

        apiReturn(200,'获取课程用户列表成功',$datas);
    }

    // 获取课程用户信息
    public function userCourseInfo()
    {
        $data = input();//token id课程用户id
        $userCourseInfo = db('user_course')->field('id,realname,phone')->where('id',$data['id'])->find();
        apiReturn(200,'获取课程用户信息成功',$userCourseInfo);
    }

    // 删除课程用户
    public function userCourseDelete()
    {
        $data = input();//token id课程用户id
        if (empty($data['id'])) {
            apiReturn(201,'课程用户id为空');
        }
        db('user_course')->delete($data['id']);
        apiReturn(200,'删除成功');
    }

    // 导入用户
    public function userCourseImport()
    {
        $data = input();//token凭证 url文件路径 action_type操作类型(1导入用户 2导入删除)
        if (empty($data['url'])) {
            apiReturn(202,'文件不能为空');
        }
        if (empty($data['action_type'])) {
            apiReturn(203,'操作类型不能为空');
        }
        $data_array = excels::readExcelFile($data['url']);
        if (empty($data_array)) {
            apiReturn(204,'文件内容为空或读取失败');
        }
        if ($data['action_type'] == 1) {
            foreach ($data_array as $key => $value) {
                if ($key >= 1) {
                    if (!empty($value[0])) {
                        $exist = db('user_course')->where('phone',trim($value[1]))->find();
                        $datas = array(
                            'realname'=>$value[0],
                            'phone'=>trim($value[1]),
                            'date'=>time()
                        );
                        if (empty($exist)) {
                            db('user_course')->insert($datas);
                        }else{
                            db('user_course')->where('id',$exist['id'])->update($datas);
                        }
                    }
                }
            }
            apiReturn(200,'导入成功');
        }elseif ($data['action_type'] == 2) {
            foreach ($data_array as $key => $value) {
                if ($key >= 1) {
                    if (!empty($value[0])) {
                        $exist = db('user_course')->where('phone',trim($value[1]))->find();
                        if (!empty($exist)) {
                            db('user_course')->where(array('realname'=>$value[0],'phone'=>trim($value[1])))->delete();
                        }
                    }
                }
            }
            apiReturn(200,'删除成功');
        }else{
            apiReturn(205,'操作类型错误');
        }
    }

    /*
     * 来源获取链
     * */
    public function get_media_next(){
        $media = input('media');
        if(empty($media)) apiReturn(400,'缺少参数');
        $media_type = CrmMediaNext::where('media_id',CrmMedia::where('media',$media)->value('id'))->column('type');
        if(!is_array($media_type) || count($media_type)<=0)apiReturn(400,'该渠道没有添加链');
        apiReturn(200,'成功',$media_type[array_rand($media_type,1)]);
    }

    public function blw_user(){
        $data = input();
        if (empty($data['phone'])){
            apiReturn(400,'请输入手机号');
        }
        if (empty($data['course_id'])){
            apiReturn(400,'请输入子课程id');
        }
        if (empty($data['month'])){
            apiReturn(400,'请选择观看日期');
        }
        $startDay = strtotime($data['month'])*1000;
        $endDay = strtotime(date('Y-m-d', strtotime($data['month']." +1 month -1 day")))*1000;
        $user_id = UserCourse::where('phone',$data['phone'])->value('id');
        if(!$user_id)apiReturn(400,'手机号输入错误：tp_user_course不存在此用户');
        $link = GoodsNext::where('id',$data['course_id'])->value('link');
        $link =explode('/',$link);
        $channelId = $link[count($link)-1];
        $res = Blw::statistics_user($user_id,$channelId,$startDay,$endDay);
        if(is_null($res)) apiReturn(400,'保利威无观看记录');
        if(is_string($res)) apiReturn(400,$res);
        $blw_data=[];
        foreach ($res['data']['contents'] as $k=>$v){
            $blw_data[$k]['user_course_id']=$v['param1'];
            $blw_data[$k]['name']=$v['param2'];
            $blw_data[$k]['playDuration']=$this->changeTimeType($v['playDuration']);
            $blw_data[$k]['stayDuration']=$this->changeTimeType($v['stayDuration']);
            $blw_data[$k]['channelId']=$v['channelId'];
            $blw_data[$k]['referer']=$v['referer'];
        }
        apiReturn(200,'成功',$blw_data);

    }
    private  function  changeTimeType($seconds)
    {
        if ($seconds > 3600) {
            $hours = intval($seconds / 3600);
            $time = $hours . ":" . gmstrftime('%M:%S', $seconds);
        } else {
            $time = gmstrftime('%H:%M:%S', $seconds);
        }
        return $time;
    }

}
